package com.freeman.cement.controller;

import com.freeman.cement.annotation.NeedRole;
import com.freeman.cement.entity.PhoneRecord;
import com.freeman.cement.entity.ResponseResult;
import com.freeman.cement.exception.AppException;
import com.freeman.cement.exception.AppExceptionCodeMsg;
import com.freeman.cement.service.PhoneService;
import com.freeman.cement.service.impl.PhoneServiceImpl;
import com.freeman.cement.util.ConfigUtil;
import com.freeman.cement.util.HttpClientUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 电话服务
 * 1、调用电话设备的电话服务拨打电话
 * 2、接收电话设备的通话完毕回调，记录通话录音文件存放地址
 * 3、根据报警事件id查询与之相关的通话记录
 */
@RestController
@RequestMapping("/phone")
@CrossOrigin    //允许跨域访问
public class PhoneController {
    private static Logger logger = LoggerFactory.getLogger(PhoneController.class);

    @Resource
    PhoneService phoneService;

    /**
     * 根据事件id分页查找通话记录
     */
    @NeedRole("管理员||值班员")
    @RequestMapping(value = "/selectPhoneRecord", method = RequestMethod.POST)
    public ResponseResult selectPhoneRecord(@RequestParam String eventId, @RequestParam int pageNo, @RequestParam int pageSize) {
        return phoneService.selectPhoneRecordByEventId(eventId, pageNo, pageSize);
    }

    /**
     * 拨打电话服务
     */
    @NeedRole("管理员||值班员")
    @RequestMapping(value = "/makeCall", method = RequestMethod.POST)
    public ResponseResult makeCall(
            String recordId,
            @RequestParam String eventId,
            @RequestParam int callerId,
            String callerName,
            @RequestParam String callerNum,
            @RequestParam int recvId,
            String recvName,
            @RequestParam String recvNum) {
        String MakeCallUrl, PhoneCallbackUrl;
        try {
            MakeCallUrl = ConfigUtil.readKey("MakeCallUrl");
            PhoneCallbackUrl = ConfigUtil.readKey("PhoneCallbackUrl");
        } catch (IOException e) {
            e.printStackTrace();
            MakeCallUrl = null;
            PhoneCallbackUrl = null;
            logger.error("makeCall--->" + "拨打电话服务调用失败:" + e.toString());
        }
        if (StringUtils.isNotBlank(MakeCallUrl) && StringUtils.isNotBlank(PhoneCallbackUrl)) {
            //如果录音文件未命名则系统命名
            if(StringUtils.isBlank(recordId))
            {
                recordId =  callerNum + "-" + recvNum + "-" + (new Date().getTime());
            }
            Map<String, String> map = new HashMap<>();
            map.put("record_id", recordId);
            map.put("callback_url", PhoneCallbackUrl);
            map.put("local_num", callerNum);
            map.put("callout_num", recvNum);

            String rslt = "调用电话拨号服务失败";
            rslt = HttpClientUtil.doGet(MakeCallUrl, map, 5000, 5000);

            //操作结果存入数据库
            PhoneRecord record = new PhoneRecord();
            record.setRecordId(recordId);
            record.setEventId(eventId);
            record.setCallerId(callerId);
            record.setCallerName(callerName);
            record.setCallerNum(callerNum);
            record.setRecvId(recvId);
            record.setRecvName(recvName);
            record.setRecvNum(recvNum);
            record.setDailTime(new Date());
            phoneService.addPhoneRecord(record);

            if (StringUtils.isNotBlank(rslt)) {
                return ResponseResult.successMsg(rslt);
            } else {
                throw new AppException(AppExceptionCodeMsg.CALL_PHONE_SERVICE_ERROR);
            }

        } else {
            throw new AppException(50021, "拨打电话服务调用失败，未配置电话服务地址");
        }
    }

    /**
     * 接收通话完毕回调，记录通话录音文件存放地址
     */
    @RequestMapping(value = "/phoneCallback", method = RequestMethod.POST)
    public void phoneCallback(String recordId, String recordPath)
    {
        if(StringUtils.isNotBlank(recordId) && StringUtils.isNotBlank(recordPath)){
            PhoneRecord record = new PhoneRecord();
            record.setRecordId(recordId);
            record.setRecord(recordPath);
            phoneService.updatePhoneRecord(record);
        }
    }
}
